Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [1]:
# Load pickled data
import pickle

# TODO: Fill this in based on where you saved the training and testing data

training_file = "./train-data/train.p"
validation_file= "./train-data/valid.p"
testing_file = "./train-data/test.p"

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [2]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results
import numpy as np

# TODO: Number of training examples
n_train = len(X_train)

# TODO: Number of testing examples.
n_test = len(X_test)

# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape
image_depth = image_shape[2]

# TODO: How many unique classes/labels there are in the dataset.
n_classes = np.unique(y_train).shape[0]

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Depth of data =", image_depth)
print("Number of classes =", n_classes)
Number of training examples = 34799
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Depth of data = 3
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [3]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import random
import cv2
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.utils import shuffle
from mpl_toolkits.axes_grid1 import ImageGrid


# Visualizations will be shown in the notebook.
%matplotlib inline

def show_image(images, index):
    image = images[index].squeeze()
    #print("min ", np.amin(image[:,:,0]), np.amax(image[:,:,0]))
    plt.figure(figsize=(1,1))
    plt.imshow(image)
    print(y_train[index])
    
def show_single_image(image, index):
    #image = images[index].squeeze()
    #print("min ", np.amin(image[:,:,0]), np.amax(image[:,:,0]))
    print("Type ", index, trafficSignName(index))
    plt.figure(figsize=(1,1))
    plt.imshow(image)
    print(y_train[index])
    
def compare_images(src1, src2, index, src3 = None, src4 = None):
    print("Type ", index, trafficSignName(index))
    ncols = 2
    if src3 != None:
        ncols += 1
    if src4 != None:
        ncols += 1
    fig = plt.figure(1, (4., 4.))
    grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(1, ncols),  # creates 1xn grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )
    grid[0].imshow(src1)
    grid[1].imshow(src2)
    if src3 != None:
        grid[2].imshow(src3)
    if src4 != None:
        grid[3].imshow(src4)
    plt.show()

traffic_labels = pd.read_csv('signnames.csv', sep=',')

def trafficSignName(num):
    return traffic_labels[traffic_labels['ClassId']==num]['SignName'][num]

fig, ax = plt.subplots()

# the histogram of the data
hist, bins, patches = ax.hist(y_train, n_classes)
print("hist ", hist)

ax.set_xlabel('Label Id')
ax.set_ylabel('Number of Images')
ax.set_title(r'Train Image Distribution')

# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()

# Augment the training set
'''
shape = X_train.shape
X_aug = np.empty([0, shape[1], shape[2], shape[3]], dtype = X_train.dtype)
y_aug = np.empty([0], dtype = y_train.dtype)

X_aug = np.append(X_aug, X_train, axis = 0)
y_aug = np.append(y_aug, y_train)

print("shape ", X_train.shape, X_aug.shape)
print("shape ", y_train.shape, y_aug.shape)

show_flag = np.zeros((n_classes), dtype=int)
for j in range(shape[0]):
    image = None
    image1 = None
    image2 = None

    if y_train[j] == 11 or \
        y_train[j] == 13 or \
        y_train[j] == 18 or \
        y_train[j] == 19 or \
        y_train[j] == 20 or \
        y_train[j] == 22 or \
        y_train[j] == 26 or \
        y_train[j] == 30 or \
        y_train[j] == 33 or \
        y_train[j] == 34 or \
        y_train[j] == 35 or \
        y_train[j] == 36 or \
        y_train[j] == 37 or \
        y_train[j] == 38 or \
        y_train[j] == 39:
        image = cv2.flip(X_train[j], 1)
    elif y_train[j] == 32 or y_train[j] == 41:
        image = cv2.flip(X_train[j], -1)
    elif y_train[j] == 12 or y_train[j] == 15 or y_train[j] == 17:
        image = cv2.flip(X_train[j], 1)
        image1 = cv2.flip(X_train[j], 0)
        image2 = cv2.flip(X_train[j], -1)
        
    
    if image != None:
        if show_flag[y_train[j]] == 0:
            compare_images(X_train[j], image, y_train[j], image1, image2)
            show_flag[y_train[j]] = 1
        image = np.expand_dims(image, axis=0)
        X_aug = np.append(X_aug, image, axis = 0)
        
        if image1 != None:
            image1 = np.expand_dims(image1, axis = 0)
            X_aug = np.append(X_aug, image1, axis= 0)
            
        if image2 != None:
            image2 = np.expand_dims(image2, axis = 0)
            X_aug = np.append(X_aug, image2, axis= 0)
        if y_train[j] == 19:
            y_aug = np.append(y_aug, 20)
        elif y_train[j] == 20:
            y_aug = np.append(y_aug, 19)
        elif y_train[j] == 33:
            y_aug = np.append(y_aug, 34)
        elif y_train[j] == 34:
            y_aug = np.append(y_aug, 33)
        elif y_train[j] == 36:
            y_aug = np.append(y_aug, 37)
        elif y_train[j] == 37:
            y_aug = np.append(y_aug, 36)
        elif y_train[j] == 38:
            y_aug = np.append(y_aug, 39)
        elif y_train[j] == 39:
            y_aug = np.append(y_aug, 38)
        elif y_train[j] == 12 or y_train[j] == 15 or y_train[j] == 17:
            y_aug = np.append(y_aug, y_train[j])
            y_aug = np.append(y_aug, y_train[j])
            y_aug = np.append(y_aug, y_train[j])
        else:
            y_aug = np.append(y_aug, y_train[j])

X_train = X_aug
y_train = y_aug

print("shape ", X_train.shape)
print("shape ", y_train.shape)
fig, ax = plt.subplots()

# the histogram of the data
hist, bins, patches = ax.hist(y_train, n_classes)
print("hist ", hist)

ax.set_xlabel('Label Id')
ax.set_ylabel('Number of Images')
ax.set_title(r'Augmented Train Image Distribution')

# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()
'''

target_num = np.int(np.max(hist) * 3 / 2)
print("target ", target_num)

target_total = target_num * n_classes
print("target total", target_total)

shape = X_train.shape

X_aug = np.zeros((target_total, shape[1], shape[2], shape[3]), dtype= X_train.dtype)
y_aug = np.zeros((target_total), dtype= y_train.dtype)

X_aug[0:shape[0],:,:,:] = X_train
y_aug[0:shape[0]] = y_train

p = shape[0]
show_flag = np.zeros((n_classes), dtype=int)
for i in range(n_classes):
    n = np.count_nonzero(y_train == i)
    pad_n = np.int(target_num - n)
    
    l = np.where(y_train == i)
    l = shuffle(l[0])
    #print("i: ", i, "l :", l)
    points = np.random.randint(low=0, high = 4, size=(pad_n, 3, 2))
    #print("points ", points)
    index = 0
    for j in range(pad_n):
        src = np.array([[32,32],[63,32],[32,63]])
        dst = src + points[j]
        #dst[0][0] += points[j][0][0]
        #dst[0][1] += points[j][0][1]
        #dst[1][0] -= points[j][1][0]
        #dst[1][1] += points[j][1][1]
        #dst[2][0] += points[j][2][0]
        #dst[2][1] -= points[j][2][1]

        warp_mat = cv2.getAffineTransform(np.float32(src), np.float32(dst))
        if index == n:
            index = 0
        image_expand = cv2.copyMakeBorder(X_train[l[index]], 32, 32, 32, 32, cv2.BORDER_REPLICATE)
        image_expand = cv2.warpAffine(image_expand,warp_mat, (96,96))
        image = image_expand[32:64,32:64,:]
        if show_flag[i] == 0:
            #print("src ", src)
            #print("dst ", dst)
            compare_images(X_train[l[index]], image, i)
            show_flag[i] = 1
        #image = np.expand_dims(image, axis = 0)
        X_aug[p] = image
        y_aug[p] = i
        p += 1
        index += 1

show_num = 12
selected_pics = np.zeros([n_classes, show_num])

X_train = X_aug
y_train = y_aug

# the histogram of the data
fig, ax = plt.subplots()
hist, bins, patches = ax.hist(y_train, n_classes)

ax.set_xlabel('Label Id')
ax.set_ylabel('Number of Images')
ax.set_title(r'Augmented Train Image Distribution')

# Tweak spacing to prevent clipping of ylabel
fig.tight_layout()
plt.show()

for i in range(n_classes):
    #n = np.count_nonzero(y_train == i)
    #hist.append(n)
    #condlist = [y_train == i]
    #choicelist = [range(n_train)]
    l = np.where(y_train == i)
    l = shuffle(l[0])
    print("label[ ", i, "]:", hist[i], " name: ", trafficSignName(i))

    fig = plt.figure(1, (8., 8.))
    grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(1, show_num),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )
    for j in range(show_num):
        im = X_train[l[j]]
        selected_pics[i][j] = l[j]
        grid[j].imshow(im)
    plt.show()

n_train = len(X_train)

n_test = len(X_test)

image_shape = X_train[0].shape
image_depth = image_shape[2]

print("Number of training examples =", n_train)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Depth of data =", image_depth)
hist  [  180.  1980.  2010.  1260.  1770.  1650.   360.  1290.  1260.  1320.
  1800.  1170.  1890.  1920.   690.   540.   360.   990.  1080.   180.
   300.   270.   330.   450.   240.  1350.   540.   210.   480.   240.
   390.   690.   210.   599.   360.  1080.   330.   180.  1860.   270.
   300.   210.   210.]
target  3015
target total 129645
Type  0 Speed limit (20km/h)
Type  1 Speed limit (30km/h)
Type  2 Speed limit (50km/h)
Type  3 Speed limit (60km/h)
Type  4 Speed limit (70km/h)
Type  5 Speed limit (80km/h)
Type  6 End of speed limit (80km/h)
Type  7 Speed limit (100km/h)
Type  8 Speed limit (120km/h)
Type  9 No passing
Type  10 No passing for vehicles over 3.5 metric tons
Type  11 Right-of-way at the next intersection
Type  12 Priority road
Type  13 Yield
Type  14 Stop
Type  15 No vehicles
Type  16 Vehicles over 3.5 metric tons prohibited
Type  17 No entry
Type  18 General caution
Type  19 Dangerous curve to the left
Type  20 Dangerous curve to the right
Type  21 Double curve
Type  22 Bumpy road
Type  23 Slippery road
Type  24 Road narrows on the right
Type  25 Road work
Type  26 Traffic signals
Type  27 Pedestrians
Type  28 Children crossing
Type  29 Bicycles crossing
Type  30 Beware of ice/snow
Type  31 Wild animals crossing
Type  32 End of all speed and passing limits
Type  33 Turn right ahead
Type  34 Turn left ahead
Type  35 Ahead only
Type  36 Go straight or right
Type  37 Go straight or left
Type  38 Keep right
Type  39 Keep left
Type  40 Roundabout mandatory
Type  41 End of no passing
Type  42 End of no passing by vehicles over 3.5 metric tons
label[  0 ]: 3015.0  name:  Speed limit (20km/h)
label[  1 ]: 3015.0  name:  Speed limit (30km/h)
label[  2 ]: 3015.0  name:  Speed limit (50km/h)
label[  3 ]: 3015.0  name:  Speed limit (60km/h)
label[  4 ]: 3015.0  name:  Speed limit (70km/h)
label[  5 ]: 3015.0  name:  Speed limit (80km/h)
label[  6 ]: 3015.0  name:  End of speed limit (80km/h)
label[  7 ]: 3015.0  name:  Speed limit (100km/h)
label[  8 ]: 3015.0  name:  Speed limit (120km/h)
label[  9 ]: 3015.0  name:  No passing
label[  10 ]: 3015.0  name:  No passing for vehicles over 3.5 metric tons
label[  11 ]: 3015.0  name:  Right-of-way at the next intersection
label[  12 ]: 3015.0  name:  Priority road
label[  13 ]: 3015.0  name:  Yield
label[  14 ]: 3015.0  name:  Stop
label[  15 ]: 3015.0  name:  No vehicles
label[  16 ]: 3015.0  name:  Vehicles over 3.5 metric tons prohibited
label[  17 ]: 3015.0  name:  No entry
label[  18 ]: 3015.0  name:  General caution
label[  19 ]: 3015.0  name:  Dangerous curve to the left
label[  20 ]: 3015.0  name:  Dangerous curve to the right
label[  21 ]: 3015.0  name:  Double curve
label[  22 ]: 3015.0  name:  Bumpy road
label[  23 ]: 3015.0  name:  Slippery road
label[  24 ]: 3015.0  name:  Road narrows on the right
label[  25 ]: 3015.0  name:  Road work
label[  26 ]: 3015.0  name:  Traffic signals
label[  27 ]: 3015.0  name:  Pedestrians
label[  28 ]: 3015.0  name:  Children crossing
label[  29 ]: 3015.0  name:  Bicycles crossing
label[  30 ]: 3015.0  name:  Beware of ice/snow
label[  31 ]: 3015.0  name:  Wild animals crossing
label[  32 ]: 3015.0  name:  End of all speed and passing limits
label[  33 ]: 3015.0  name:  Turn right ahead
label[  34 ]: 3015.0  name:  Turn left ahead
label[  35 ]: 3015.0  name:  Ahead only
label[  36 ]: 3015.0  name:  Go straight or right
label[  37 ]: 3015.0  name:  Go straight or left
label[  38 ]: 3015.0  name:  Keep right
label[  39 ]: 3015.0  name:  Keep left
label[  40 ]: 3015.0  name:  Roundabout mandatory
label[  41 ]: 3015.0  name:  End of no passing
label[  42 ]: 3015.0  name:  End of no passing by vehicles over 3.5 metric tons
Number of training examples = 129645
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Depth of data = 3

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture (is the network over or underfitting?)
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

Pre-process the Data Set (normalization, grayscale, etc.)

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

In [4]:
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import cv2

def yuv_normalization(images):
    output = np.ndarray(images.shape, dtype=np.float64)
    for i, image in enumerate(images):
        img = np.float64(image)
        mean = np.mean(img[:,:,0], dtype = np.float64)
        img[:,:,0] -= mean
        img = img / 256.0
        output[i] = img
    return output

def rescale_normalized_yuv(image):
    #print("image ", image)
    image[:,:,0] = image[:,:,0] * 128 + 128
    image[:,:,1] = image[:,:,1] * 256
    image[:,:,2] = image[:,:,2] * 256
    #print("image ", image)
    return np.uint8(image)

def rgb2yuv(images):
    output = np.ndarray(images.shape, dtype=np.uint8)
    for i, image in enumerate(images):
        image = cv2.cvtColor(image, cv2.COLOR_RGB2YUV)
        image[:,:,0] = cv2.equalizeHist(image[:,:,0])
        output[i] = image
    return output

X_train_yuv = rgb2yuv(X_train)
X_test_yuv = rgb2yuv(X_test)
X_valid_yuv = rgb2yuv(X_valid)

X_train_norm = yuv_normalization(X_train_yuv)
X_test_norm = yuv_normalization(X_test_yuv)
X_valid_norm = yuv_normalization(X_valid_yuv)

print("train: global min ", np.min(X_train[:,:,:,0]), np.min(X_train[:,:,:,1]), np.min(X_train[:,:,:,2]))
print("processed: global min ", np.min(X_train_yuv[:,:,:,0]), np.min(X_train_yuv[:,:,:,1]), np.min(X_train_yuv[:,:,:,2]))
print("normalized: global min ", np.min(X_train_norm[:,:,:,0]), np.min(X_train_norm[:,:,:,1]), np.min(X_train_norm[:,:,:,2]))
print("train: global max ", np.max(X_train[:,:,:,0]), np.max(X_train[:,:,:,1]), np.max(X_train[:,:,:,2]))
print("processed: global max ", np.max(X_train_yuv[:,:,:,0]), np.max(X_train_yuv[:,:,:,1]), np.max(X_train_yuv[:,:,:,2]))
print("normalized: global max ", np.max(X_train_norm[:,:,:,0]), np.max(X_train_norm[:,:,:,1]), np.max(X_train_norm[:,:,:,2]))
print("train: global mean ", np.mean(X_train[:,:,:,0]), np.mean(X_train[:,:,:,1]), np.mean(X_train[:,:,:,2]))
print("processed: global mean ", np.mean(X_train_yuv[:,:,:,0]), np.mean(X_train_yuv[:,:,:,1]), np.mean(X_train_yuv[:,:,:,2]))
print("normalized: global mean ", np.mean(X_train_norm[:,:,:,0]), np.mean(X_train_norm[:,:,:,1]), np.mean(X_train_norm[:,:,:,2]))
#print("shape ", X_train.shape)
#print("type ", X_train.dtype)
image_depth = X_train_norm[0].shape[2]
train: global min  0 3 0
processed: global min  0 46 0
normalized: global min  -0.721462249756 0.1796875 0.0
train: global max  255 255 255
processed: global max  255 228 250
normalized: global max  0.573833465576 0.890625 0.9765625
train: global mean  87.5760421111 81.2770655338 84.0581635337
processed: global mean  131.238625188 130.31892154 129.089267439
normalized: global mean  0.0 0.509058287264 0.504254950934
In [5]:
def show_processed_images(X_yuv, X_norm, indecis, y, num_classes, num_images):
    shape = X_yuv[0].shape
    tmp = np.zeros((num_images, shape[0], shape[1], shape[2]), dtype=X_yuv.dtype)
    
    shape = X_norm[0].shape
    tmp_norm = np.zeros((num_images, shape[0], shape[1], shape[2]), dtype=X_norm.dtype)
    for i in range(num_classes):
        n = np.count_nonzero(y == i)
        print("label[ ", i, "]:", n, " name: ", trafficSignName(i))
        
        for j in range(num_images):
            tmp[j] = X_yuv[indecis[i][j]]
            tmp_norm[j] = X_norm[indecis[i][j]]
        #print("tmp type", tmp.dtype)
        #print("train type", X_train_processed.dtype)

        #print("Y: ")
        fig = plt.figure(1, (8., 8.))
        grid = ImageGrid(fig, 111,  # similar to subplot(111)
                     nrows_ncols=(1, num_images),  # creates 2x2 grid of axes
                     axes_pad=0.1,  # pad between axes in inch.
                     )
        for j in range(num_images):
            grid[j].imshow(tmp[j,:,:,0], cmap='gray')
        plt.show()
    
        #print("U: ")
        fig = plt.figure(1, (8., 8.))
        grid = ImageGrid(fig, 111,  # similar to subplot(111)
                     nrows_ncols=(1, num_images),  # creates 2x2 grid of axes
                     axes_pad=0.1,  # pad between axes in inch.
                     )
        for j in range(num_images):
            grid[j].imshow(tmp[j,:,:,1], cmap='gray')
        plt.show()

        #print("V: ")
        fig = plt.figure(1, (8., 8.))
        grid = ImageGrid(fig, 111,  # similar to subplot(111)
                     nrows_ncols=(1, num_images),  # creates 2x2 grid of axes
                     axes_pad=0.1,  # pad between axes in inch.
                     )
        for j in range(num_images):
            grid[j].imshow(tmp[j,:,:,1], cmap='gray')
        plt.show()

        #print("Color: ")
        fig = plt.figure(1, (8., 8.))
        grid = ImageGrid(fig, 111,  # similar to subplot(111)
                     nrows_ncols=(1, num_images),  # creates 2x2 grid of axes
                     axes_pad=0.1,  # pad between axes in inch.
                     )
        for j in range(num_images):
            #print("dtype ", tmp[j].dtype)
            tmp[j] = cv2.cvtColor(tmp[j], cv2.COLOR_YUV2RGB)
            grid[j].imshow(tmp[j])
        plt.show()
    
        fig = plt.figure(1, (8., 8.))
        grid = ImageGrid(fig, 111,  # similar to subplot(111)
                     nrows_ncols=(1, num_images),  # creates 2x2 grid of axes
                     axes_pad=0.1,  # pad between axes in inch.
                     )
        for j in range(num_images):
            #print("dtype ", tmp[j].dtype)
            img = rescale_normalized_yuv(tmp_norm[j])
            img = cv2.cvtColor(img, cv2.COLOR_YUV2RGB)
            grid[j].imshow(img)
        plt.show()


show_processed_images(X_train_yuv, X_train_norm, selected_pics, y_train, n_classes, show_num)
label[  0 ]: 3015  name:  Speed limit (20km/h)
/home/carnd/anaconda3/envs/carnd-term1/lib/python3.5/site-packages/ipykernel/__main__.py:12: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
/home/carnd/anaconda3/envs/carnd-term1/lib/python3.5/site-packages/ipykernel/__main__.py:13: VisibleDeprecationWarning: using a non-integer number instead of an integer will result in an error in the future
label[  1 ]: 3015  name:  Speed limit (30km/h)
label[  2 ]: 3015  name:  Speed limit (50km/h)
label[  3 ]: 3015  name:  Speed limit (60km/h)
label[  4 ]: 3015  name:  Speed limit (70km/h)
label[  5 ]: 3015  name:  Speed limit (80km/h)
label[  6 ]: 3015  name:  End of speed limit (80km/h)
label[  7 ]: 3015  name:  Speed limit (100km/h)
label[  8 ]: 3015  name:  Speed limit (120km/h)
label[  9 ]: 3015  name:  No passing
label[  10 ]: 3015  name:  No passing for vehicles over 3.5 metric tons
label[  11 ]: 3015  name:  Right-of-way at the next intersection
label[  12 ]: 3015  name:  Priority road
label[  13 ]: 3015  name:  Yield
label[  14 ]: 3015  name:  Stop
label[  15 ]: 3015  name:  No vehicles
label[  16 ]: 3015  name:  Vehicles over 3.5 metric tons prohibited
label[  17 ]: 3015  name:  No entry
label[  18 ]: 3015  name:  General caution
label[  19 ]: 3015  name:  Dangerous curve to the left
label[  20 ]: 3015  name:  Dangerous curve to the right
label[  21 ]: 3015  name:  Double curve
label[  22 ]: 3015  name:  Bumpy road
label[  23 ]: 3015  name:  Slippery road
label[  24 ]: 3015  name:  Road narrows on the right
label[  25 ]: 3015  name:  Road work
label[  26 ]: 3015  name:  Traffic signals
label[  27 ]: 3015  name:  Pedestrians
label[  28 ]: 3015  name:  Children crossing
label[  29 ]: 3015  name:  Bicycles crossing
label[  30 ]: 3015  name:  Beware of ice/snow
label[  31 ]: 3015  name:  Wild animals crossing
label[  32 ]: 3015  name:  End of all speed and passing limits
label[  33 ]: 3015  name:  Turn right ahead
label[  34 ]: 3015  name:  Turn left ahead
label[  35 ]: 3015  name:  Ahead only
label[  36 ]: 3015  name:  Go straight or right
label[  37 ]: 3015  name:  Go straight or left
label[  38 ]: 3015  name:  Keep right
label[  39 ]: 3015  name:  Keep left
label[  40 ]: 3015  name:  Roundabout mandatory
label[  41 ]: 3015  name:  End of no passing
label[  42 ]: 3015  name:  End of no passing by vehicles over 3.5 metric tons
In [6]:
### Define your architecture here.
### Feel free to use as many code cells as needed.

from tensorflow.contrib.layers import flatten

MU = 0
SIGMA = 0.1


def LeNet(x):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
    
    nf0 = 64
    conv0_W = tf.Variable(tf.truncated_normal(shape=(1, 1, image_depth, nf0), mean = mu, stddev = sigma))
    conv0_b = tf.Variable(tf.zeros(nf0))
    conv0 = tf.nn.conv2d(x, conv0_W, strides=[1, 1, 1, 1], padding='VALID') + conv0_b
    #32x32x8
    
    # SOLUTION: Layer 1: Convolutional. Input = 32x32x3. Output = 28x28x16.
    nf1 = 128
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, nf0, nf1), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros(nf1))
    conv1   = tf.nn.conv2d(conv0, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b
    conv1 = tf.nn.relu(conv1)
    conv1 = tf.nn.max_pool(conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
    #14x14x128

    # SOLUTION: Layer 2: Convolutional. Output = 10x10x16.
    nf2 = 256
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, nf1, nf2), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(nf2))
    conv2   = tf.nn.conv2d(conv1, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
    #10x10x256
    conv2 = tf.nn.relu(conv2)
    conv2 = tf.nn.max_pool(conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
    #conv2 = tf.nn.dropout(conv2, 0.5)
    #5x5x256

    '''
    nf3 = 64
    conv3_W = tf.Variable(tf.truncated_normal(shape=(5, 5, nf2, nf3), mean = mu, stddev = sigma))
    conv3_b = tf.Variable(tf.zeros(nf3))
    conv3   = tf.nn.conv2d(conv2, conv3_W, strides=[1, 1, 1, 1], padding='VALID') + conv3_b
    conv3 = tf.nn.relu(conv3)
    # 8x8x64
    conv3 = tf.nn.max_pool(conv3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
    #conv3 = tf.nn.dropout(conv3, 0.5)
    # 4x4x64
    '''
    
    # SOLUTION: Flatten. Input = 5x5x32. Output = 400.
    # 16x16x16
    f1 = flatten(conv1)
    # 8x8x32
    f2 = flatten(conv2)
    # 4x4x64
    #f3 = flatten(conv3)
    fc0 = tf.concat(1, [f1, f2])#, f3])
    nfc0 = 14*14*nf1 + 5*5*nf2# + 4*4*nf3
    
    # SOLUTION: Layer 3: Fully Connected. Input = 400. Output = 120.
    nfc1 = 512
    fc1_W = tf.Variable(tf.truncated_normal(shape=(nfc0, nfc1), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(nfc1))
    fc1   = tf.matmul(fc0, fc1_W) + fc1_b
    
    # SOLUTION: Activation.
    fc1    = tf.nn.relu(fc1)
    fc1 = tf.nn.dropout(fc1, 0.5)

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
    nfc2 = 256
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(nfc1, nfc2), mean = mu, stddev = sigma))
    fc2_b  = tf.Variable(tf.zeros(nfc2))
    fc2    = tf.matmul(fc1, fc2_W) + fc2_b
    
    # SOLUTION: Activation.
    fc2    = tf.nn.relu(fc2)

    # SOLUTION: Layer 4: Fully Connected. Input = 120. Output = 84.
    nfc3 = 128
    fc3_W  = tf.Variable(tf.truncated_normal(shape=(nfc2, nfc3), mean = mu, stddev = sigma))
    fc3_b  = tf.Variable(tf.zeros(nfc3))
    fc3    = tf.matmul(fc2, fc3_W) + fc3_b
    
    # SOLUTION: Activation.
    fc3    = tf.nn.relu(fc3)
    
    # SOLUTION: Layer 5: Fully Connected. Input = 128. Output = 10.
    fc4_W  = tf.Variable(tf.truncated_normal(shape=(nfc3, n_classes), mean = mu, stddev = sigma))
    fc4_b  = tf.Variable(tf.zeros(n_classes))
    logits = tf.matmul(fc3, fc4_W) + fc4_b
    
    return logits

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [7]:
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.

import tensorflow as tf
from sklearn.utils import shuffle

EPOCHS = 20
BATCH_SIZE = 128

x = tf.placeholder(tf.float32, (None, 32, 32, image_depth))
#v = tf.placeholder(tf.float32, (None, 32, 32, image_depth))
y = tf.placeholder(tf.int32, (None))
one_hot_y = tf.one_hot(y, n_classes)

# Training pipeline
rate = 0.001

logits = LeNet(x)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits, one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = rate)
training_operation = optimizer.minimize(loss_operation)


#evaluation

correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver = tf.train.Saver()

def evaluate(X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    sess = tf.get_default_session()
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples

# training the model

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_train_norm)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        X_train_norm, y_train = shuffle(X_train_norm, y_train)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_train_norm[offset:end], y_train[offset:end]
            sess.run(training_operation, feed_dict={x: batch_x, y: batch_y})
            
        validation_accuracy = evaluate(X_valid_norm, y_valid)
        print("EPOCH {} ...".format(i+1))
        print("Validation Accuracy = {:.3f}".format(validation_accuracy))
        print()
        
    saver.save(sess, './lenet')
    print("Model saved")
    
# Test the model
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    test_accuracy = evaluate(X_test_norm, y_test)
    print("Test Accuracy = {:.3f}".format(test_accuracy))
Training...

EPOCH 1 ...
Validation Accuracy = 0.867

EPOCH 2 ...
Validation Accuracy = 0.898

EPOCH 3 ...
Validation Accuracy = 0.929

EPOCH 4 ...
Validation Accuracy = 0.938

EPOCH 5 ...
Validation Accuracy = 0.938

EPOCH 6 ...
Validation Accuracy = 0.948

EPOCH 7 ...
Validation Accuracy = 0.949

EPOCH 8 ...
Validation Accuracy = 0.951

EPOCH 9 ...
Validation Accuracy = 0.954

EPOCH 10 ...
Validation Accuracy = 0.950

EPOCH 11 ...
Validation Accuracy = 0.948

EPOCH 12 ...
Validation Accuracy = 0.951

EPOCH 13 ...
Validation Accuracy = 0.958

EPOCH 14 ...
Validation Accuracy = 0.965

EPOCH 15 ...
Validation Accuracy = 0.960

EPOCH 16 ...
Validation Accuracy = 0.963

EPOCH 17 ...
Validation Accuracy = 0.966

EPOCH 18 ...
Validation Accuracy = 0.965

EPOCH 19 ...
Validation Accuracy = 0.961

EPOCH 20 ...
Validation Accuracy = 0.966

Model saved
Test Accuracy = 0.944

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [8]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.

import os
import os.path
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from mpl_toolkits.axes_grid1 import ImageGrid
import numpy as np
import pandas as pd

'''
directory = 'test-data/'

file_num = len(os.listdir(directory))

file_list = []
for root, dirs, files in os.walk(directory, topdown=False):
    for i, fn in enumerate(files):
        img_name = directory+fn
        if img_name.lower().endswith('.bmp'):
            #print("image: ", img_name)
            #image = mpimg.imread(img_name)
            #plt.imshow(image)
            #plt.show()
            file_list.append(img_name)
print("file list:", file_list)
print("num: ", len(file_list))
'''

test_file = pd.read_csv('test.csv', sep=',')
test_y = test_file['ClassId'].as_matrix()
file_list = test_file['FilePath'].as_matrix()

#print('test y:', test_y.shape)
#print('test file:', file_list.shape)
#print("test file size: ", test_file.shape)
#print("test file path: ", test_file['FilePath'])
#print('test file type: ', test_file['ClassId'])

num_pic = len(file_list)
num_col = 8
num_row = np.int((num_pic + 8) / 8)
print("row ", num_row)
fig = plt.figure(1, (8., 8.))
grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(num_row, num_col),  # creates 2x2 grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                )
for j in range(num_pic):
    grid[j].imshow(mpimg.imread(file_list[j]))
    
plt.draw()
plt.show()

#label = (27, 8, 8, 13, 25, 14)
row  6

Predict the Sign Type for Each Image

In [9]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
import cv2
import numpy as np

test_array = np.zeros((num_pic, 32, 32, 3), dtype = np.uint8)

for j in range(num_pic):
    test_array[j] = mpimg.imread(file_list[j])

'''
def norm_and_equal(data):
    data = cv2.equalizeHist(data)
    image = data / 255.0
    mean = np.mean(image, dtype = np.float64)
    #image -= mean
    return image

def preprocess(images):
    shape = images.shape
    output = np.ndarray([shape[0], shape[1], shape[2], 1])
    for i, image in enumerate(images):
        image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
        image = cv2.equalizeHist(image)
        image = image / 255.0
        image = np.expand_dims(image, axis=2)
        mean = np.mean(image, dtype=np.float64)
        image -= mean
        output[i] = image
    return output
'''

test_yuv = rgb2yuv(test_array)
test_data = yuv_normalization(test_yuv)

image_depth = test_data[0].shape[2]

Analyze Performance

In [10]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.

import tensorflow as tf

#n_classes = 43

#x = tf.placeholder(tf.float32, (None, 32, 32, image_depth))
#y = tf.placeholder(tf.int32, (None))
#one_hot_y = tf.one_hot(y, n_classes)

# Training pipeline
#rate = 0.001

#logits = LeNet(x)

#evaluation

#correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
#accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#saver = tf.train.Saver()
do_test_operation = tf.argmax(logits, 1)

def test_operation(X_data, y_data):
    sess = tf.get_default_session()
    result = sess.run(do_test_operation, feed_dict={x: X_data, y: y_data})
    return result

'''
def evaluate_test(X_data, y_data):
    total_accuracy = 0
    sess = tf.get_default_session()
    total_accuracy = sess.run(accuracy_operation, feed_dict={x: X_data, y: y_data})
    return total_accuracy
    '''
#label = np.array([27, 8, 8, 13, 25, 14])

# Test the model
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    test_accuracy = evaluate(test_data, test_y)
    #result = test_operation(test_data, label)
    print("Test accuracy = ", test_accuracy)
Test accuracy =  0.765957474709

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [25]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.
import tensorflow as tf
import matplotlib.gridspec as gridspec

#n_classes = 43

#x = tf.placeholder(tf.float32, (None, 32, 32, image_depth))
#y = tf.placeholder(tf.int32, (None))
#one_hot_y = tf.one_hot(y, n_classes)

# Training pipeline
#rate = 0.001

#logits = LeNet(x)

#evaluation

#correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
#accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#saver = tf.train.Saver()
do_test_operation = tf.argmax(logits, 1)
top5 = tf.nn.top_k(tf.nn.softmax(logits), k=5)

def test_operation(X_data, y_data):
    sess = tf.get_default_session()
    result = sess.run(top5, feed_dict={x: X_data, y: y_data})
    return result

'''
def evaluate_test(X_data, y_data):
    total_accuracy = 0
    sess = tf.get_default_session()
    total_accuracy = sess.run(accuracy_operation, feed_dict={x: X_data, y: y_data})
    return total_accuracy
    '''
label = np.array([27, 8, 8, 13, 25, 14])
#print("shape ", X_train.shape)
#print("shape ", y_train.shape)
#print("type ", y_train.dtype)
#print("shape ", test_data.shape)
#print("shape ", label.shape)
# Test the model
with tf.Session() as sess:
    saver.restore(sess, tf.train.latest_checkpoint('.'))

    #test_accuracy = evaluate(test_data, label)
    top = test_operation(test_data, label)
    #print("Top 5 result = ", top)


def show_image_with_top5(files, index, label, top):
    print("No. ", index, " File: ", files[index])
    #print("Type: ", label[index], trafficSignName(label[index]))
    values = top.values[index]
    indices = top.indices[index]
    '''
    print("Pre: ", indices[0], trafficSignName(indices[0]), values[0])
    print("Pre: ", indices[1], trafficSignName(indices[1]), values[1])
    print("Pre: ", indices[2], trafficSignName(indices[2]), values[2])
    print("Pre: ", indices[3], trafficSignName(indices[3]), values[3])
    print("Pre: ", indices[4], trafficSignName(indices[4]), values[4])
    '''
    image = mpimg.imread(files[index])
    '''
    fig = plt.figure(1, (4., 4.))
    grid = ImageGrid(fig, 111,  # similar to subplot(111)
                 nrows_ncols=(1, 1),  # creates 1xn grid of axes
                 axes_pad=0.1,  # pad between axes in inch.
                 )
    grid[0].imshow(image)
    plt.show()
    '''
    if indices[0] == label[index]:
        show_color = 'green'
    else:
        show_color = 'red'
    plt.figure(figsize = (5,1.5))
    gs = gridspec.GridSpec(1, 2,width_ratios=[2,3])
    plt.subplot(gs[0])
    plt.imshow(image)
    plt.axis('off')
    plt.subplot(gs[1])
    plt.barh(6 - np.arange(5), values, align='center', color = show_color)
    for i in range(5):
        text = trafficSignName(indices[i])
        if values[i] < 0.1:
            text += "    < 0.1"
        else:
            text += "    " + str(values[i])
        plt.text(values[0] + .02, 6- i - .25, text)
    plt.axis('off');
    plt.text(0,6.95, trafficSignName(label[index]));
    plt.show();


for i in range(num_pic):
    show_image_with_top5(file_list, i, test_y, top)
No.  0  File:  test-data/96822779.bmp
No.  1  File:  test-data/5.bmp
No.  2  File:  test-data/3.bmp
No.  3  File:  test-data/688071187.bmp
No.  4  File:  test-data/171590640.bmp
No.  5  File:  test-data/689937191.bmp
No.  6  File:  test-data/2.bmp
No.  7  File:  test-data/142475664.bmp
No.  8  File:  test-data/6367584752.bmp
No.  9  File:  test-data/459381359.bmp
No.  10  File:  test-data/106352829.bmp
No.  11  File:  test-data/171209328.bmp
No.  12  File:  test-data/689937195.bmp
No.  13  File:  test-data/469763319.bmp
No.  14  File:  test-data/465649993.bmp
No.  15  File:  test-data/165186251.bmp
No.  16  File:  test-data/57452573.bmp
No.  17  File:  test-data/459381113.bmp
No.  18  File:  test-data/532364055.bmp
No.  19  File:  test-data/122911974.bmp
No.  20  File:  test-data/649124149.bmp
No.  21  File:  test-data/96150383.bmp
No.  22  File:  test-data/678876687.bmp
No.  23  File:  test-data/646712504.bmp
No.  24  File:  test-data/636758475.bmp
No.  25  File:  test-data/469763309.bmp
No.  26  File:  test-data/1063528292.bmp
No.  27  File:  test-data/139372530.bmp
No.  28  File:  test-data/6.bmp
No.  29  File:  test-data/122439599.bmp
No.  30  File:  test-data/153951752.bmp
No.  31  File:  test-data/125530335.bmp
No.  32  File:  test-data/656334061.bmp
No.  33  File:  test-data/459381295.bmp
No.  34  File:  test-data/4.bmp
No.  35  File:  test-data/459380825.bmp
No.  36  File:  test-data/97447859.bmp
No.  37  File:  test-data/459381275.bmp
No.  38  File:  test-data/1.bmp
No.  39  File:  test-data/95909520.bmp
No.  40  File:  test-data/674491693.bmp
No.  41  File:  test-data/1539517522.bmp
No.  42  File:  test-data/548310403.bmp
No.  43  File:  test-data/607770600.bmp
No.  44  File:  test-data/688963145.bmp
No.  45  File:  test-data/142641434.bmp
No.  46  File:  test-data/155907900.bmp

Step 4: Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [22]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it maybe having trouble accessing the variable from inside a function
    activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(15,15))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")

Question 9

Discuss how you used the visual output of your trained network's feature maps to show that it had learned to look for interesting characteristics in traffic sign images

Answer:

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.